import { h, inject, ref } from 'vue';

let IDCache = -1;

const CreateID = () => {
    return IDCache--;
}

export const InitMapping = (ParamConfig, DefaultValue) => {
    const ParamMapping = ref({});
    const ChangeValueEvents = {};
    const ChangeOptionEvents = {};
    const DictMapping = {};
    const Value = {};
    const WacthEventMapping = {};


    ParamConfig.forEach(element => {
        ParamMapping.value[element.Key] = element;
        if (element.Event && element.Event.Value) {
            ChangeValueEvents[element.Key] = element.Event.Value;
        }
        if (element.Event && element.Event.Wacth) {
            for (const key in element.Event.Wacth) {
                const _element = element.Event.Wacth[key];
                if (!WacthEventMapping[key]) {
                    WacthEventMapping[key] = {};
                };
                WacthEventMapping[key][element.Key] = _element;
            };
        }

        if (element.Event && element.Event.Option) {
            ChangeOptionEvents[element.Key] = element.Event.Option;
        }
        if (element.hasOwnProperty('Dict') && !Array.isArray(element.Dict)) {
            const DictValue = element.Dict.split(':');
            if (DictValue.length == 3) {
                const [Parentkey, Child, Default] = DictValue;
                if (!DictMapping[Parentkey]) {
                    DictMapping[Parentkey] = {}
                }
                DictMapping[Parentkey][element.Key] = {
                    Key: Child,
                    Default: Default
                }
            }
        }
        if (DefaultValue && DefaultValue.hasOwnProperty(element.Key)) {
            Value[element.Key] = DefaultValue[element.Key]
        } else if (element.hasOwnProperty('Default')) {
            Value[element.Key] = element.Default
        } else {
            switch ((element.Type + '').toLowerCase()) {
                case 'string':
                    Value[element.Key] = '';
                    break;
                case 'Radio':
                    Value[element.Key] = '';
                    break;
                case 'CheckBox':
                    Value[element.Key] = false;
                    break;
                case 'number':
                    Value[element.Key] = 0;
                    break;
                case 'int':
                    Value[element.Key] = 0;
                    break;
                case 'primary':
                    Value[element.Key] = CreateID();
                    break;
                default:
                    Value[element.Key] = null;
                    break;
            }
        }
    });

    console.log(Value);

    return {
        ParamMapping,
        WacthEventMapping,
        ChangeValueEvents,
        ChangeOptionEvents,
        DictMapping,
        Value: ref({ ...DefaultValue, ...Value })
    }
};


